<?php

namespace app\admin\service;

use app\admin\model\ModuleModel;
use think\facade\App;

class ModuleService extends BaseService
{
    //系统模块隐藏
    const SYSTEM_MODULE_LIST = ['admin','common'];

    /**
     * 获取本地模块列表
     *
     * @Author tanruizheng
     * @DateTime 2021-07-30
     * @return void
     */
    public static function getModuleList(){
        $appPath = App::getRootPath().'/app/';
        $scandir = scandir($appPath);
        $dirsList = [];
        foreach($scandir as $key => $val){
            if($val != '.' && $val != '..'){
                if(is_dir($appPath . $val)){
                    if(in_array($val,self::SYSTEM_MODULE_LIST)){
                        continue;
                    }
                    $dirsList[$val] = $appPath . $val . '/Config.inc.php';
                }
            }
        }
        $moduleList = [];
        foreach ($dirsList as $module => $moduleFilePath) {
            if(!is_file($moduleFilePath)){
                continue;
            }
            $moduleInfo = ModuleModel::where('module',$module)->findOrEmpty()->toArray();
            $config = [
                'module'        =>  $module,
                'modulename'    =>  '',
                'author'        =>  '',
                'introduce'     =>  '',
                'authoremail'   =>  '',
                'version'       =>  '',
                'adaptation'    =>  '',
                'install_time'  =>  $moduleInfo ? date('Y-m-d H:i:s',$moduleInfo['installtime']) : '',
            ];
            $moduleConfig = include $moduleFilePath;
            $moduleList[] = array_merge($config,$moduleConfig);
        }
        return self::createList($moduleList, 0);
    }

    /**
     * 获取模块信息
     *
     * @Author tanruizheng
     * @DateTime 2021-07-30
     * @param [type] $module
     * @return void
     */
    public static function getModuleInfo($module){
        $configFile = base_path() . strtolower("{$module}/") . "/Config.inc.php";
        if(!file_exists($configFile)){
            return self::createFail('配置文件不存在');
        }
        $moduleConfig = include $configFile;
        $moduleConfig['install_time'] = '';
        $moduleInfo = ModuleModel::where('module',$module)->findOrEmpty();
        if(!$moduleInfo->isEmpty()){
            $moduleConfig['install_time'] = $moduleInfo->install_time;
        }
        return self::createSuccess('ok',$moduleConfig);
    }
}